import os
import re

'''
这个函数接受一个文件夹路径作为参数，并列出该文件夹下所有文件的完整路径。
'''
def list_files_in_directory(directory_path):
    # 获取文件夹下所有文件和子文件夹的列表
    all_items = os.listdir(directory_path)
    resultList = []
    # 遍历所有项目
    for item in all_items:
        # 拼接文件夹路径和项目名，得到完整路径
        full_path = os.path.join(directory_path, item)
        
        # 判断该路径是否为文件
        if os.path.isfile(full_path):
            # 如果是文件，则打印其完整路径
            resultList.append(full_path)
    return resultList

def open_file_filter_str_list(file_path):
    result_str_list = []
    # 正则表达式模式，用于模糊匹配包含'DROP'的字符串
    pattern = re.compile(r"DROP", re.IGNORECASE)
    # 打开文件
    with open(file_path, 'r', encoding='utf-8') as file:
        # 读取文件的所有行
        lines = file.readlines()
        # 遍历列表，逐行输出文件内容
        for line in lines:
            if pattern.search(line) and hasNumberStr(line):
                result_str_list.append(line.strip())  # 使用strip()方法去除每行末尾的换行符
    return result_str_list

'''
判断有数字
'''
def hasNumberStr(line):
    line = line.strip()
    pattern = re.compile(r'\d{4,}')
    if pattern.search(line):
        return True
    return False

'''
获取表名
'''
def getTableName(file_path):
    # 正则表达式获取表名
    pattern = re.compile(r"Source Database", re.IGNORECASE)
    # 打开文件
    with open(file_path, 'r', encoding='utf-8') as file:
        # 读取文件的所有行
        lines = file.readlines()
        # 遍历列表，逐行输出文件内容
        for line in lines:
            if pattern.search(line):
                return line.strip().replace("Source Database       : ","")
    return None

def printFile(sql_list,table_name):
    if not os.path.exists("resource"):
        os.makedirs("resource")
    current_file_path = os.path.dirname(os.path.abspath(__file__))+"\\resource\\{}.sql".format(table_name)
    # 将内容写入文件
    with open(current_file_path, 'w', encoding='utf-8') as file:
        for line in sql_list:
            file.write(line.replace("DROP TABLE IF EXISTS ","DROP TABLE IF EXISTS `{}`.".format(table_name))+"\n")

if __name__ == "__main__":
    # 获取文件夹路径
    filePath = input("输入文件夹路径:\n")
    file_list = list_files_in_directory(filePath)

    for item in file_list:
        tableName = getTableName(item)
        sqlList = open_file_filter_str_list(item)
        printFile(sqlList,tableName)
